package com.jingming.consult.database;

import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import androidx.room.Transaction;
import androidx.room.Update;

import com.jingming.consult.bean.usercenter.UserInfo;
@Dao
public abstract class UserDao {
    @Transaction
    public long inertUserInfo(UserInfo userInfo) {
        if (userInfo == null) {
            return -1;
        }
        UserInfo dbUserInfo = dbGetUserInfoByMemcard(userInfo.getMemcard());
        if (dbUserInfo != null) {
            userInfo.setId(dbUserInfo.getId());//使用主键进行更新
            return dbUpdateUserInfo(userInfo);
        }
        return dbInsertUserInfo(userInfo);
    }

    /**
     * 查询对应的memcard 用户数据
     *
     * @param memcard memcard
     * @return UserInfo
     */
    @Query("select * from table_userinfo where memcard=:memcard")
    public abstract UserInfo dbGetUserInfoByMemcard(String memcard);

    /**
     * 插入用户信息
     *
     * @param user UserInfo
     * @return 是否插入成功
     */
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    protected abstract long dbInsertUserInfo(UserInfo user);


    @Transaction
    public int deleteUserInfo(String memcard) {
        UserInfo dbUserInfo = dbGetUserInfoByMemcard(memcard);
        if (dbUserInfo != null) {
            return dbDeleteUser(dbUserInfo);
        }
        return -1;
    }

    /**
     * 删除用户数据
     *
     * @param userInfo
     * @return 是否删除成功
     */
    @Delete
    public abstract int dbDeleteUser(UserInfo userInfo);

    /**
     * 更新用户数据
     *
     * @param userInfo dbUpdateUserInfo
     * @return 是否更新成功
     */

    @Update(onConflict = OnConflictStrategy.REPLACE)
    abstract int dbUpdateUserInfo(UserInfo userInfo);

    /**
     * 更新memcard字段
     *
     * @param memcard 用户表示
     * @return 是否更新成功
     */
    @Query("update table_userinfo set memcard = :memcard ")
    public abstract int dbUpdateMemcard(String memcard);

}
